/**
 * 给定一个正整数 n，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的正方形矩阵。
 * <p>
 * 示例:
 * <p>
 * 输入: 3
 * 输出:
 * [
 * [ 1, 2, 3 ],
 * [ 8, 9, 4 ],
 * [ 7, 6, 5 ]
 * ]
 */
class Solution {

    public static void main(String[] args) {
        System.out.println(generateMatrix(4).length);
    }

    public static int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        generateMatrix(result, n, 1);
        return result;
    }

    public static void generateMatrix(int[][] result, int n, int num) {
        if (n == 0) {
            return;
        }
        // 算出需要处理的区域
        int start = (result.length - n) / 2;
        int end = result.length - 1 - start;
        if (n == 1) {
            result[start][end] = num;
            return;
        }
        for (int i = start; i <= end; i++) {
            result[start][i] = num++;
        }
        for (int i = start + 1; i <= end; i++) {
            result[i][end] = num++;
        }
        for (int i = end - 1; i >= start; i--) {
            result[end][i] = num++;
        }
        for (int i = end - 1; i > start; i--) {
            result[i][start] = num++;
        }
        generateMatrix(result, n - 2, num);
    }
}